import React, { useState, useEffect } from "react";
import { UndoOutlined, UnorderedListOutlined, AppstoreOutlined, LineHeightOutlined, SearchOutlined, PlusOutlined, MinusCircleOutlined } from '@ant-design/icons';
import { Button, Table, Modal, Radio, DatePicker, message } from 'antd';
// import style from './PTK.module.css'
import style from '../../cssmodule/PTK.module.css'
import dayjs from 'dayjs';
import axios from 'axios';
import * as XLSX from 'xlsx';


// 项目任务列表
const ProjectTaskList = () => {
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [selectedValueOne, setSelectedValueOne] = useState(null);
  const [selectedValueTwo, setSelectedValueTwo] = useState(null);
  const [tasks, setTasks] = useState([]);
  const [searchQuery, setSearchQuery] = useState('');
  const [isPreviewModalOpen, setIsPreviewModalOpen] = useState(false);
  const [previewData, setPreviewData] = useState(null);
  const [viewMode, setViewMode] = useState('list'); // 'list' or 'card'

  const fetchTasks = async (query = '') => {
    try {
      const response = await axios.get('/api/pticklist/list', { params: { name: query } });
      if (response.data.code === 200) {
        setTasks(response.data.data);
      } else {
        message.error('获取任务列表失败');
      }
    } catch (error) {
      message.error('获取任务列表失败');
    }
  };

  useEffect(() => {
    fetchTasks();
  }, []);

  const showModal = () => {
    setIsModalOpen(true);
  };

  const handleOk = () => {
    setIsModalOpen(false);
    console.log('选中的值:', selectedValueOne, selectedValueTwo);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };

  const onChangeRadioOne = (e) => {
    setSelectedValueOne(e.target.value);
  };
  const onChangeRadioTwo = (e) => {
    setSelectedValueTwo(e.target.value);
  }
  const [pdfFile, setPdfFile] = useState(null);
  const handlePdfChange = (event) => {
    if (event.target.files && event.target.files[0]) {
      setPdfFile(event.target.files[0]);
    }
  };
  const handleWordChange = (event) => {
    if (event.target.files && event.target.files[0]) {
      setWordFile(event.target.files[0]);
    }
  };

  const onChangeTime = (date, dateString) => {
    console.log(date, dateString);
  };

  const [taskRows, setTaskRows] = useState([
    { name: '', start: '', end: '', period: '', hour: '', code: '', status: '未开始', remark: '' },
  ]);

  const handleTaskChange = (idx, key, value) => {
    const newRows = [...taskRows];
    newRows[idx][key] = value;
    setTaskRows(newRows);
  };
  const handleTaskDateChange = (idx, key, date) => {
    const newRows = [...taskRows];
    newRows[idx][key] = date ? date.format('YYYY-MM-DD') : '';
    // 自动计算工期天数和工时数
    const start = newRows[idx].start;
    const end = newRows[idx].end;
    if (start && end) {
      const startDate = dayjs(start, 'YYYY-MM-DD');
      const endDate = dayjs(end, 'YYYY-MM-DD');
      const days = endDate.diff(startDate, 'day') + 1;
      newRows[idx].period = days > 0 ? `${days}天` : '';
      newRows[idx].hour = days > 0 ? `${days * 8}h` : '';
    } else {
      newRows[idx].period = '';
      newRows[idx].hour = '';
    }
    setTaskRows(newRows);
  };
  const addTaskRow = () => {
    setTaskRows([...taskRows, { name: '', start: '', end: '', period: '', hour: '', code: '', status: '未开始', remark: '' }]);
  };
  const removeTaskRow = (idx) => {
    if (taskRows.length > 1) {
      setTaskRows(taskRows.filter((_, i) => i !== idx));
    } else {
      message.info('至少要有一个任务');
    }
  };

  const handleSaveTasks = async () => {
    // 过滤掉未填写的任务
    const tasksToSave = taskRows.filter(task => task.name.trim() !== '');
    if (tasksToSave.length === 0) {
      message.warning('请输入任务信息');
      return;
    }
    try {
      const response = await axios.post('/api/pticklist/add', tasksToSave);
      if (response.data.code === 200) {
        message.success('添加成功');
        setIsModalOpen(false);
        fetchTasks(); // 重新获取任务列表
        // 重置表单
        setTaskRows([{ name: '', start: '', end: '', period: '', hour: '', code: '', status: '未开始', remark: '' }]);
      } else {
        message.error('添加失败: ' + response.data.message);
      }
    } catch (error) {
      message.error('添加失败');
    }
  };

  const handleDeleteTask = async (id) => {
    try {
      const response = await axios.post(`/api/pticklist/delete/${id}`);
      if (response.data.code === 200) {
        message.success('删除成功');
        fetchTasks(); // 重新获取任务列表
      } else {
        message.error('删除失败: ' + response.data.message);
      }
    } catch (error) {
      message.error('删除失败');
    }
  };

  // 刷新功能
  const handleRefresh = () => {
    clearTimeout();
    message.success('正在刷新数据...');
    setSearchQuery(''); fetchTasks();
    setTimeout(() => {
      message.success('刷新完成');
    }, 1000)
  };

  const handlePreview = (record) => {
    setPreviewData(record);
    setIsPreviewModalOpen(true);
  };

  const handlePreviewCancel = () => {
    setIsPreviewModalOpen(false);
    setPreviewData(null);
  };

  const handleViewModeChange = (mode) => {
    setViewMode(mode);
  };

  const handleExportExcel = () => {
    if (tasks.length === 0) {
      message.info('没有可导出的数据');
      return;
    }

    const dataToExport = tasks.map(task => ({
      'ID': task.id,
      '状态': task.status,
      '进度': task.progress,
      '任务名称': task.name,
      '任务开始时间': task.start,
      '任务完结时间': task.end,
      '工期天数': task.period,
      '工时': task.hour,
      '实际完成时间': task.realEnd || '--',
      '实际工期天数': task.realPeriod || '--',
      '实际工时': task.realHour || '--',
      '任务成本': task.cost || '--',
      '备注': task.remark,
      '创建时间': new Date(task.createdAt).toLocaleString(),
      '更新时间': new Date(task.updatedAt).toLocaleString(),
    }));

    const ws = XLSX.utils.json_to_sheet(dataToExport);
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, "任务列表");
    XLSX.writeFile(wb, "项目任务列表.xlsx");
    message.success('导出成功！');
  };

  return (
    <>
      <div>
        <div>
          <p className={style['project-title']}>
            <span className={style['project-id']}>项目函数</span>
            <span className={style['project-id']}>项目编号</span>
            <span className={style['project-id']}>P123123231231</span>
            <span className={style['project-id']}>项目名称:</span>
            <span className={style['project-id']}>CRM系统</span>
          </p>
        </div>
        <div className={style['project-body']}>
          <div className={style['project-body-up']}>
            <div>
              <button className={style['project-button']} onClick={() => handleRefresh()}><UndoOutlined /></button>
              <Button color="cyan" variant="solid" onClick={showModal}>+新增</Button>
            </div>
            <Modal
              title={null}
              open={isModalOpen}
              onOk={handleOk}
              onCancel={handleCancel}
              width={1000}
              footer={null}
            >
              <div className={style['modal-task-header']}>添加任务</div>
              <div className={style['modal-task-baseinfo']}>
                阶段名称：后端开发 <span>阶段开始时间：2022.07.11 9:00</span> <span>阶段完结时间：2022.07.11 9:00</span> <span>阶段工期天数：55天</span> <span>阶段工时数：100h</span>
              </div>
              <table className={style['modal-task-table']}>
                <thead>
                  <tr>
                    <th>序号</th>
                    <th>任务名称</th>
                    <th>任务开始时间</th>
                    <th>任务完结时间</th>
                    <th>工期天数</th>
                    <th>工时数</th>
                    <th>工时工码</th>
                    <th>任务状态</th>
                    <th>备注</th>
                    <th>操作</th>
                  </tr>
                </thead>
                <tbody>
                  {taskRows.map((row, idx) => (
                    <tr key={idx}>
                      <td>{idx + 1}</td>
                      <td><input className={style['modal-task-input']} type="text" placeholder="请输入" value={row.name} onChange={e => handleTaskChange(idx, 'name', e.target.value)} /></td>
                      <td>
                        <DatePicker
                          className={style['modal-task-input']}
                          value={row.start ? dayjs(row.start, 'YYYY-MM-DD') : null}
                          onChange={date => handleTaskDateChange(idx, 'start', date)}
                          placeholder="请选择"
                          format="YYYY-MM-DD"
                        />
                      </td>
                      <td>
                        <DatePicker
                          className={style['modal-task-input']}
                          value={row.end ? dayjs(row.end, 'YYYY-MM-DD') : null}
                          onChange={date => handleTaskDateChange(idx, 'end', date)}
                          placeholder="请选择"
                          format="YYYY-MM-DD"
                        />
                      </td>
                      <td><input className={style['modal-task-input']} type="text" placeholder="自动计算" value={row.period} disabled /></td>
                      <td><input className={style['modal-task-input']} type="text" placeholder="自动计算" value={row.hour} disabled /></td>
                      <td><input className={style['modal-task-input']} type="text" placeholder="请输入" value={row.code} onChange={e => handleTaskChange(idx, 'code', e.target.value)} /></td>
                      <td>
                        <select className={style['modal-task-select']} value={row.status} onChange={e => handleTaskChange(idx, 'status', e.target.value)}>
                          <option value="未开始">未开始</option>
                          <option value="进行中">进行中</option>
                          <option value="已完成">已完成</option>
                        </select>
                      </td>
                      <td><input className={style['modal-task-input']} type="text" placeholder="请输入" value={row.remark} onChange={e => handleTaskChange(idx, 'remark', e.target.value)} /></td>
                      <td className={style['modal-task-op']}>
                        <button className={style['modal-task-op-btn']} onClick={() => addTaskRow()} title="添加"><PlusOutlined /></button>
                        <button className={style['modal-task-op-btn']} onClick={() => removeTaskRow(idx)} title="删除"><MinusCircleOutlined /></button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
              <div className={style['modal-task-footer']}>
                <button className={style['modal-task-btn']} onClick={handleSaveTasks}>保存</button>
                <button className={style['modal-task-btn'] + ' ' + style['modal-task-btn-cancel']} onClick={handleCancel}>取消</button>
              </div>
            </Modal>
            {/* 预览模态框 */}
            {previewData && (
              <Modal
                title="任务详情预览"
                open={isPreviewModalOpen}
                onCancel={handlePreviewCancel}
                footer={[
                  <Button key="close" onClick={handlePreviewCancel}>
                    关闭
                  </Button>
                ]}
              >
                <div>
                  <p><strong>ID:</strong> {previewData.id}</p>
                  <p><strong>任务名称:</strong> {previewData.name}</p>
                  <p><strong>状态:</strong> {previewData.status}</p>
                  <p><strong>进度:</strong> {previewData.progress}</p>
                  <p><strong>任务开始时间:</strong> {previewData.start}</p>
                  <p><strong>任务完结时间:</strong> {previewData.end}</p>
                  <p><strong>工期天数:</strong> {previewData.period}</p>
                  <p><strong>工时:</strong> {previewData.hour}</p>
                  <p><strong>实际完成时间:</strong> {previewData.realEnd || '--'}</p>
                  <p><strong>实际工期天数:</strong> {previewData.realPeriod || '--'}</p>
                  <p><strong>实际工时:</strong> {previewData.realHour || '--'}</p>
                  <p><strong>任务成本:</strong> {previewData.cost || '--'}</p>
                  <p><strong>备注:</strong> {previewData.remark}</p>
                  <p><strong>创建时间:</strong> {new Date(previewData.createdAt).toLocaleString()}</p>
                  <p><strong>更新时间:</strong> {new Date(previewData.updatedAt).toLocaleString()}</p>
                </div>
              </Modal>
            )}
            <div>
              <input
                type="text"
                placeholder="按任务名称搜索"
                className={style['project-search']}
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                onKeyDown={(e) => e.key === 'Enter' && fetchTasks(searchQuery)}
              />
              <button
                className={style['project-button'] + (viewMode === 'list' ? ' ' + style['active'] : '')}
                onClick={() => handleViewModeChange('list')}
              >
                <UnorderedListOutlined />
              </button>
              <button
                className={style['project-button'] + (viewMode === 'card' ? ' ' + style['active'] : '')}
                onClick={() => handleViewModeChange('card')}
              >
                <AppstoreOutlined />
              </button>
              <button className={style['project-button']} onClick={handleExportExcel}><LineHeightOutlined /></button>
              <button className={style['project-button']} onClick={() => fetchTasks(searchQuery)}><SearchOutlined /></button>
            </div>
          </div>
          {viewMode === 'list' ? (
            <div style={{ overflowX: 'auto', marginTop: 24 }}>
              <table className={style['ptk-table']}>
                <thead>
                  <tr>
                    <th>ID</th>
                    <th>状态</th>
                    <th>进度</th>
                    <th>任务名称</th>
                    <th>任务开始时间</th>
                    <th>任务完结时间</th>
                    <th>工期天数</th>
                    <th>工时</th>
                    <th>实际完成时间</th>
                    <th>实际工期天数</th>
                    <th>实际工时</th>
                    <th>任务成本</th>
                    <th>备注</th>
                    <th>创建时间</th>
                    <th>更新时间</th>
                    <th>操作</th>
                  </tr>
                </thead>
                <tbody>
                  {tasks.map(row => (
                    <tr key={row.id}>
                      <td>{row.id}</td>
                      <td><span className={style['ptk-status'] + ' ' + style[`ptk-status-${row.statusType}`]}>{row.status}</span></td>
                      <td>{row.progress}</td>
                      <td>{row.name}{row.label && <span className={style['ptk-label']}>{row.label}</span>}</td>
                      <td>{row.start}</td>
                      <td>{row.end}</td>
                      <td>{row.period}</td>
                      <td>{row.hour}</td>
                      <td>{row.realEnd || '--'}</td>
                      <td>{row.realPeriod || '--'}</td>
                      <td>{row.realHour || '--'}</td>
                      <td>{row.cost || '--'}</td>
                      <td>{row.remark}</td>
                      <td>{new Date(row.createdAt).toLocaleString()}</td>
                      <td>{new Date(row.updatedAt).toLocaleString()}</td>
                      <td>
                        <button className={style['ptk-btn'] + ' ' + style['ptk-btn-purple']} onClick={() => handlePreview(row)}>预览</button>
                        <button className={style['ptk-btn'] + ' ' + style['ptk-btn-green']} onClick={() => handleDeleteTask(row.id)}>删除</button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
              <div className={style['ptk-table-bottom']}>
                显示第 1 到第 {tasks.length} 条记录，总共 {tasks.length} 条记录
              </div>
            </div>
          ) : (
            <div style={{ marginTop: 24 }}>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(300px, 1fr))', gap: '16px' }}>
                {tasks.map(row => (
                  <div key={row.id} style={{
                    border: '1px solid #d9d9d9',
                    borderRadius: '8px',
                    padding: '16px',
                    backgroundColor: '#fff',
                    boxShadow: '0 2px 8px rgba(0,0,0,0.1)'
                  }}>
                    <div style={{ marginBottom: '12px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                      <strong>{row.name}</strong>
                      <span style={{
                        padding: '2px 8px',
                        borderRadius: '4px',
                        fontSize: '12px',
                        backgroundColor: row.statusType === 'blue' ? '#e6f7ff' :
                          row.statusType === 'orange' ? '#fff7e6' : '#f5f5f5',
                        color: row.statusType === 'blue' ? '#1890ff' :
                          row.statusType === 'orange' ? '#fa8c16' : '#666'
                      }}>
                        {row.status}
                      </span>
                    </div>
                    <div style={{ marginBottom: '8px', fontSize: '12px', color: '#888' }}>ID: {row.id} | 进度: {row.progress}</div>
                    <div style={{ marginBottom: '8px' }}><strong>时间:</strong> {row.start} - {row.end}</div>
                    <div style={{ marginBottom: '8px' }}><strong>工期:</strong> {row.period} | <strong>工时:</strong> {row.hour}</div>
                    <div style={{ marginBottom: '12px' }}><strong>备注:</strong> {row.remark || '--'}</div>
                    <div style={{ display: 'flex', gap: '8px', justifyContent: 'flex-end', marginTop: '16px' }}>
                      <button className={style['ptk-btn'] + ' ' + style['ptk-btn-purple']} onClick={() => handlePreview(row)} style={{ fontSize: '12px', padding: '4px 8px' }}>预览</button>
                      <button className={style['ptk-btn'] + ' ' + style['ptk-btn-green']} onClick={() => handleDeleteTask(row.id)} style={{ fontSize: '12px', padding: '4px 8px' }}>删除</button>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>
      </div>
    </>
  );
}

export default ProjectTaskList;